<template>
  <div class="app-container conflict" ref="channel-conflict">
    <el-table
      :data="tableData"
      border
      :max-height="tableHeight"
      :key="isChange"
      @cell-click="cellclick"
      style="width: 100%"
      :cell-style="cellStyle"
    >
      <el-table-column width="80px" height="100px" align="center" prop="desc">
        <template slot="header">
          <span>{{ $t('edge.phase.title') }}</span>
        </template>
        <template slot-scope="scope">
          <span style="position: absolute; left: 6px; top: 4px">{{
            scope.row.id
          }}</span>
          <span style="position: absolute; left: 27%; top: 21%">
            <xdrdirselector
              Width="70px"
              Height="70px"
              Widths="60px"
              Heights="60px"
              :showlist="directionList(scope.row)"
            ></xdrdirselector>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableData"
        :key="index"
        align="center"
        prop="date"
        :label="item.id + ''"
        width="80"
      >
        <template slot="header">
          <span style="position: absolute; left: 6px; top: -6px">{{
            item.id
          }}</span>
          <span style="position: absolute; left: 20%; top: 16%">
            <xdrdirselector
              Width="70px"
              Height="70px"
              Widths="60px"
              Heights="60px"
              :showlist="directionList(item)"
            ></xdrdirselector>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px; float: right">
      <el-button type="primary" @click="defaultData">{{
        $t('edge.channel.default')
      }}</el-button>
      <!-- <el-button type="primary" @click="custom">{{$t('edge.channel.custom')}}</el-button> -->
      <el-button type="primary" @click="empty">{{
        $t('edge.channel.empty')
      }}</el-button>
    </div>
  </div>
</template>

<script>
// import { mapState } from 'vuex'
import xdrdirselector from '../../components/XRDDirSelector'
import { getTheme } from '../../utils/auth'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'
export default {
  name: 'channelconflict',
  data () {
    return {
      isChange: false,
      tableHeight: 760,
      isDefault: false,
      colorArray: [],
      selectArray: [],
      selectList: [],
      whiteList: [],
      signLocationList: [
        {
          value: 0,
          label: this.$t('edge.channel.direction0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.direction1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.direction2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.direction3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.direction4')
        },
        {
          value: 5,
          label: this.$t('edge.channel.direction5')
        },
        {
          value: 6,
          label: this.$t('edge.channel.direction6')
        },
        {
          value: 7,
          label: this.$t('edge.channel.direction7')
        }
      ],
      turnOptions: [
        {
          value: 0,
          label: this.$t('edge.channel.turn0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.turn1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.turn2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.turn3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.turn4')
        },
        {
          value: 5,
          label: this.$t('edge.channel.turn5')
        },
        {
          value: 6,
          label: this.$t('edge.channel.turn6')
        },
        {
          value: 7,
          label: this.$t('edge.channel.turn7')
        }
      ],
      channeltypeOptions: [
        {
          value: 0,
          label: this.$t('edge.channel.type0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.type1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.type2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.type3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.type4')
        }
      ],
      tableData: []
    }
  },
  components: {
    xdrdirselector
  },
  computed: {
    channelGreenConflictInfo () {
      return this.$store.getters.tscParam.channelGreenConflictInfo
    }
    // ...mapState({
    //   channelGreenConflictInfo: state => state.globalParam.tscParam.channelGreenConflictInfo
    // })
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    let channel = this.globalParamModel.getParamsByType('channelList')
    // let phaseList = this.globalParamModel.getParamsByType('phaseList')
    this.tableData = channel.map(item => {
      return {
        id: item.id,
        peddirection: item.realtype && item.realtype === 'peddirection' ? item.realdir : [],
        phasedirection: item.realtype && item.realtype === 'direction' ? item.realdir : []
        // desc: item.id + (item.type === '' || item.type === undefined ? '' : '-') + this.getTypeDesc(item.type) + ((item.direction !== '' && item.direction !== undefined) || (item.direction === '' && item.turn && item.turn.length > 0) || (item.direction === undefined && item.turn && item.turn.length > 0) ? '-' : '') + this.getDirection(item.direction) + (item.turn ? this.getTurnDesc(item.turn) : '')
      }
    })
    this.getDefaul()
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      _this.tableHeight = _this.$refs['channel-conflict'].offsetHeight - 90
      window.onresize = function () {
        _this.tableHeight = _this.$refs['channel-conflict'].offsetHeight - 90
      }
    })
  },
  methods: {
    directionList (data) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      let dirArr = []
      if (data.phasedirection) {
        if (data.phasedirection.length === 0) {
          let recd = {
            id: 0,
            peddirection: this.getPed(data.peddirection),
            color: color
          }
          dirArr.push(recd)
        } else {
          for (let rec of data.phasedirection) {
            let recd = {
              id: rec,
              peddirection: this.getPed(data.peddirection),
              color: color
            }
            dirArr.push(recd)
          }
        }
      }
      return dirArr
    },
    getPed (data) {
      if (data.length === 0) return
      let ped = []
      let peddirections = []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      for (let walk of data) {
        let objs = {}
        objs.name = new PhaseDataModel().getSidePos(walk).name
        objs.id = walk
        objs.color = color
        peddirections.push(objs)
        peddirections = Array.from(new Set(peddirections))
      }
      ped.push(...peddirections)
      return ped
    },
    defaultData () {
      this.isDefault = true
      this.getDefaul()
      this.globalParamModel.deleteParams('channelGreenConflictInfo')
      this.globalParamModel.addParamsChannelGreen('channelGreenConflictInfo', this.colorArray)
    },
    getDefaul () {
      let phaseList = this.globalParamModel.getParamsByType('phaseList')
      let overlaplList = this.globalParamModel.getParamsByType('overlaplList')
      let channel = this.globalParamModel.getParamsByType('channelList')
      let newPhase = phaseList.map(item => {
        return {
          id: item.id,
          concurrent: item.concurrent
        }
      })
      let newOverlap = overlaplList.map(item => {
        return {
          id: item.id,
          includedphases: item.includedphases
        }
      })
      let newChannel = channel.map(item => {
        return {
          id: item.id,
          controltype: item.controltype,
          controlsource: item.controlsource
        }
      })
      let defaultList = newChannel.map(cha => {
        if (cha.controltype === 2 || cha.controltype === 3) {
          for (let i = 0; i < newPhase.length; i++) {
            if (cha.controlsource === newPhase[i].id) {
              return {
                id: cha.id,
                controlsource: cha.controlsource,
                newCurren: newPhase[i].concurrent
              }
            }
          }
        } else if (cha.controltype === 4 || cha.controltype === 5) {
          let newLap = newOverlap.map(item => {
            let phaList = []
            if (item.id === cha.controlsource) {
              phaList.push(...item.includedphases)
            }
            // for (let h = 0; h < item.includedphases.length; h++) {
            //   for (let k = 0; k < newPhase.length; k++) {
            //     if (item.includedphases[h] === newPhase[k].id) {
            //       phaList.push(...newPhase[k].concurrent)
            //     }
            //   }
            // }
            return {
              id: item.id,
              concurrent: Array.from(new Set(phaList))
            }
          })
          for (let i = 0; i < newLap.length; i++) {
            if (cha.controlsource === newLap[i].id) {
              return {
                id: cha.id,
                controlsource: newLap[i].concurrent,
                newCurren: newLap[i].concurrent
              }
            }
          }
        } else {
          return {
            id: cha.id,
            controlsource: cha.controlsource,
            newCurren: []
          }
        }
      })
      // this.colorArray = this.transform(defaultList)
      const ret = defaultList.map((i, idx) => {
        const result = []
        let greenconflict = []
        defaultList.forEach((j, jdx) => {
          if (idx !== jdx) {
            const ic = Array.isArray(i.controlsource) ? i.controlsource : [i.controlsource]
            const jc = Array.isArray(j.controlsource) ? j.controlsource : [j.controlsource]
            let hasDuplicate = false
            for (let i = 0; i < ic.length; i++) {
              for (let j = 0; j < jc.length; j++) {
                if (ic[i] === jc[j]) {
                  hasDuplicate = true
                  break
                }
              }
              if (hasDuplicate) {
                break
              }
            }
            const isRelation = ic.some(x => jc.some(y => newPhase.find(m => m.id === x && m.concurrent.includes(y))))
            if (isRelation || hasDuplicate) {
              result.push(j.id)
            } else {
              greenconflict.push(j.id)
            }
          }
        })
        i.result = result
        i.greenconflict = greenconflict
        return i
      })
      let newFlict = ret.map(r => {
        return {
          channelid: r.id,
          greenOther: r.result,
          greenconflict: r.greenconflict
        }
      })
      this.colorArray = newFlict
      this.whiteList = newFlict
    },
    // transform (arr) {
    //   return arr.map(item => {
    //     const { id, controlsource } = item
    //     let newObj = {
    //       channelid: id,
    //       greenOther: item.newCurren.length === 0 ? [] : arr.filter(x => x.newCurren.includes(controlsource) && x.id !== id).map(y => y.id),
    //       greenconflict: item.newCurren.length === 0 ? [] : arr.filter(x => !x.newCurren.includes(controlsource) && x.id !== id).map(y => y.id)
    //     }
    //     this.whiteList.push(newObj)
    //     return {
    //       channelid: id,
    //       greenOther: item.newCurren.length === 0 ? [] : arr.filter(x => x.newCurren.includes(controlsource) && x.id !== id).map(y => y.id),
    //       greenconflict: item.newCurren.length === 0 ? [] : arr.filter(x => !x.newCurren.includes(controlsource) && x.id !== id).map(y => y.id)
    //     }
    //   })
    // },
    empty () {
      this.isDefault = false
      this.colorArray = []
      this.selectList = []
      this.selectArray = []
      this.globalParamModel.deleteParams('channelCustom')
      this.globalParamModel.deleteParams('channelGreenConflictInfo')
    },
    // getTurnDesc (val) {
    //   if (!val) return
    //   if (val.length === 0) {
    //     return ''
    //   } else {
    //     let turnDesc = this.turnOptions.filter((v) => val.some((item) => item === v.value))
    //     return turnDesc.map((j) => {
    //       return j.label
    //     }).join(',')
    //   }
    // },
    // getDirection (val) {
    //   if (val === undefined || val === '') {
    //     return ''
    //   } else {
    //     let directioDesc = this.signLocationList.filter(item => item.value === val)[0]
    //     return directioDesc.label
    //   }
    // },
    // getTypeDesc (val) {
    //   if (val === undefined || val === '') {
    //     return ''
    //   } else {
    //     let typeDesc = this.channeltypeOptions.filter(item => item.value === val)[0]
    //     return typeDesc.label
    //   }
    // },
    cellclick (row, column, cell, event) {
      if (!column.label) return
      if (Number(row.id) === Number(column.label)) return
      // if (Number(row.desc.replace(/[^0-9]/ig, '')) === Number(column.label)) return// 1,1 2,2不可点击
      let obj = {
        id: Number(row.id),
        label: Number(column.label)
      }
      if (this.channelGreenConflictInfo.length === 0) {
        if (JSON.stringify(this.selectArray).includes(JSON.stringify(obj)) === false) {
          for (let d = 0; d < this.whiteList.length; d++) {
            if (!this.whiteList[d].greenOther.includes(obj.label) && this.whiteList[d].channelid === obj.id) { // greenOther控制白色方块
              this.selectArray.push(obj)
              this.computeList(this.selectArray)
            }
          }
        } else {
          for (let l = 0; l < this.selectArray.length; l++) {
            if (this.selectArray[l].id === obj.id && this.selectArray[l].label === obj.label) {
              this.selectArray.splice(this.selectArray.findIndex(i => (i.label === obj.label && i.id === obj.id)), 1)
            }
          }
          for (let f = 0; f < this.selectList.length; f++) {
            if (this.selectList[f].channelid === obj.id && this.selectList[f].greenconflict.includes(obj.label)) {
              this.selectList[f].greenconflict.splice(this.selectList[f].greenconflict.findIndex(i => (i === obj.label)), 1)
              this.selectList.filter(item => item.channelid === obj.label)[0].greenconflict.splice(this.selectList.filter(item => item.channelid === obj.label)[0].greenconflict.findIndex(i => (i === obj.id)), 1)
            }
          }
        }
        this.globalParamModel.addParamsChannelGreen('channelCustom', this.selectList)
      } else {
        for (let i = 0; i < this.channelGreenConflictInfo.length; i++) {
          let whiteOther = this.whiteList.filter(x => x.channelid === this.channelGreenConflictInfo[i].channelid)[0]
          if (this.channelGreenConflictInfo[i].channelid === obj.id && this.channelGreenConflictInfo[i].greenconflict.includes(obj.label)) {
            this.channelGreenConflictInfo[i].greenconflict.splice(this.channelGreenConflictInfo[i].greenconflict.findIndex(i => (i === obj.label)), 1)
            this.channelGreenConflictInfo.filter(item => item.channelid === obj.label)[0].greenconflict.splice(this.channelGreenConflictInfo.filter(item => item.channelid === obj.label)[0].greenconflict.findIndex(i => (i === obj.id)), 1)
          } else if (this.channelGreenConflictInfo[i].channelid === obj.id && !this.channelGreenConflictInfo[i].greenconflict.includes(obj.label) && !whiteOther.greenOther.includes(obj.label) && whiteOther.greenOther.length > 0) {
            //! this.channelGreenConflictInfo[h].greenOther.includes(obj.label) && this.channelGreenConflictInfo[h].greenOther.length > 0
            this.channelGreenConflictInfo.filter(item => item.channelid === obj.label)[0].greenconflict.push(obj.id)
            this.channelGreenConflictInfo[i].greenconflict.push(obj.label)
          }
        }
      }
      this.isChange = !this.isChange
    },
    // changeArray (val) {
    //   let map = {}
    //   let dest = []
    //   for (let i = 0; i < val.length; i++) {
    //     let ai = val[i]
    //     if (!map[ai.id]) {
    //       dest.push({
    //         channelid: ai.id,
    //         greenconflict: [ai.label]
    //       })
    //       map[ai.id] = ai
    //     } else {
    //       for (let j = 0; j < dest.length; j++) {
    //         let dj = dest[j]
    //         if (dj.channelid === ai.id) {
    //           dj.greenconflict.push(ai.label)
    //           dj.greenconflict.sort()
    //           break
    //         }
    //       }
    //     }
    //   }
    //   this.selectList = dest
    //   // this.globalParamModel.addParamsChannelGreen('channelGreenConflictInfo', dest)
    // },
    computeList (val) {
      let map = {}
      let dest = []
      let newDest = []
      let channels = []
      for (let i = 0; i < val.length; i++) {
        let ai = val[i]
        if (!map[ai.id]) {
          dest.push({
            channelid: ai.id,
            greenconflict: [ai.label]
          })
          map[ai.id] = ai
        } else {
          for (let j = 0; j < dest.length; j++) {
            let dj = dest[j]
            if (dj.channelid === ai.id) {
              dj.greenconflict.push(ai.label)
              dj.greenconflict.sort()
              break
            }
          }
        }
      }
      dest.map(item => {
        item.greenconflict.map(k => {
          let newObj = {
            channelid: k,
            greenconflict: [item.channelid]
          }
          newDest.push(newObj)
        })
      })
      channels = [...dest, ...newDest]
      this.setInfo(channels)
    },
    setInfo (arr) {
      let map = {}
      let dests = []
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i]
        if (!map[ai.channelid]) {
          dests.push({
            channelid: ai.channelid,
            greenconflict: ai.greenconflict
          })
          map[ai.channelid] = ai
        } else {
          for (var j = 0; j < dests.length; j++) {
            var dj = dests[j]
            if (dj.channelid === ai.channelid) {
              dj.greenconflict = [...dj.greenconflict, ...ai.greenconflict]
              break
            }
          }
        }
      }
      this.selectList = dests
      // this.globalParamModel.deleteParams('channelGreenConflictInfo')
      // this.globalParamModel.addParamsChannelGreen('channelGreenConflictInfo', dests)
    },
    cellStyle (row, rowIndex, column) {
      if (!row.column.label) return
      if (!this.channelGreenConflictInfo) return
      // let label = Number(row.column.label.replace(/[^0-9]/ig, ''))
      let label = Number(row.column.label)
      if (Number(row.row.id) === Number(row.column.label)) {
        return 'background-color:#3a445b;'
      }
      for (let i = 0; i < (this.channelGreenConflictInfo.length === 0 ? this.selectList.length : this.channelGreenConflictInfo.length); i++) {
        if (this.channelGreenConflictInfo.length === 0) {
          if (this.selectList[i].channelid === Number(row.row.id) && this.selectList[i].greenconflict.includes(label)) {
            return 'background-color:red;'
          }
        } else {
          if (this.channelGreenConflictInfo[i].channelid === Number(row.row.id) && this.channelGreenConflictInfo[i].greenconflict && this.channelGreenConflictInfo[i].greenconflict.includes(label)) {
            return 'background-color:red;'
          }
          // 未选中的格子添加颜色区分
          if (this.channelGreenConflictInfo[i].channelid === Number(row.row.id) && this.channelGreenConflictInfo[i].greenOther && this.channelGreenConflictInfo[i].greenOther.includes(label)) {
            return 'background-color:#3a445b;'
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
.conflict {
  //  .el-table th, .el-table td{
  //       padding: 12px 0 !important;
  //   }
  .el-table--enable-row-transition .el-table__body td.el-table__cell {
    width: 80px;
    height: 74px;
  }
  .el-table th.el-table__cell > .cell {
    height: 59px;
  }
}
</style>
